import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { constant_Index_JwtConstants } from '../constants';
import { UserClient_Service } from '@/modules/businessModule/userClient/userClient.service';
import { UserAdmin_Service } from '@/modules/businessModule/userAdmin/userAdmin.service';
import { IJwtStrategyPayload } from '../typeScripts';

/**
 * @description JWT 认证策略类，用于处理 JWT 认证。
 * @extends {PassportStrategy(Strategy)}
 */
@Injectable()
export class Class_JwtStrategy_Base extends PassportStrategy(Strategy) {
  /**
   * 创建一个 Class_JwtStrategy_Base 实例。
   * @param {UserClient_Service} userClient_Service - 处理 web 用户相关服务。
   * @param {UserAdmin_Service} userAdmin_Service - 处理后台用户相关服务。
   */
  constructor(
    private readonly userClient_Service: UserClient_Service,
    private readonly userAdmin_Service: UserAdmin_Service,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: constant_Index_JwtConstants.secret,
    });
  }

  /**
   * 验证并解析 JWT 负载。
   * @param {IJwtStrategyPayload} payload - JWT 负载，包含用户信息。
   * @returns {Promise<IJwtStrategyPayload>} - 返回包含用户信息的对象。
   */
  async validate(payload: IJwtStrategyPayload): Promise<IJwtStrategyPayload> {
    const user =
      payload.type === 'web' || payload.type === 'webWx'
        ? await this.userClient_Service.userClient_FindOneById({ id: payload.userId })
        : await this.userAdmin_Service.userAdmin_FindOneByQuery({ id: payload.userId });
    return { ...payload, statusUser: user.statusUser };
  }
}
